package com.xdxc.controller;

import com.xdxc.model.dto.ExamSubmitDto;
import com.xdxc.model.dto.ExamingDto;
import com.xdxc.model.dto.UserAnswerDto;
import com.xdxc.model.form.QuestionRequestForm;
import com.xdxc.response.Result;
import com.xdxc.service.ExamRecordService;
import com.xdxc.service.ExamsService;
import com.xdxc.service.UserAnswerService;
import com.xdxc.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

@Slf4j
@RestController
@RequestMapping("/exam")
public class ExaminingController {
    @Autowired
    private ExamRecordService examRecordService;
    @Autowired
    private ExamsService examsService;

    private final RocketMQTemplate rocketMQTemplate;

    // 推荐使用构造器注入
    public ExaminingController(@Autowired(required = false) RocketMQTemplate rocketMQTemplate) {
        this.rocketMQTemplate = rocketMQTemplate;
    }

    @Autowired
    private  UserAnswerService userAnswerService;
    private static final Logger logger = LoggerFactory.getLogger(ExaminingController.class);

    @GetMapping("/creat-paper")
    public Result createExamRecord(@RequestParam Long examId, @RequestParam Long userId) {
        if (!userId.equals(SecurityUtils.getCurrentUserId())){
            return Result.error("something gonna wrong");
        }

        Long  savedId=  examRecordService.createExamRecord(examId,userId);
        if (savedId==null){
            return Result.error("错误");
        }


        HashMap<String,String> map =new HashMap<>();
        map.put("paperId", String.valueOf(savedId));
        return Result.success(map);
    }

    @GetMapping("/paper-detail")
    public Result paperData( @RequestParam Long paperId) {

        ExamingDto examingDto =examRecordService.returnPaperData(paperId);
        return Result.success(examingDto);
    }

    @PostMapping("/qu-detail")
    public Result paperData(@RequestBody QuestionRequestForm questionRequest) {
        Long quId=questionRequest.getQuId();
        Long paperId=questionRequest.getPaperId();
        if(quId==null||paperId==null){
            return Result.success("数据有误");
        }
        return examRecordService.getQuestionById(quId,paperId);
    }


    @PostMapping("/saveAnswer")
    public Result saveAnswer(@RequestBody UserAnswerDto userAnswerDto) {
        if (rocketMQTemplate == null) {
            return Result.error("消息服务暂不可用");
        }
        log.info("收到提交请求，checkId={}", userAnswerDto.getCheckId());

       Result result= userAnswerService.saveUserAnswer(userAnswerDto.getPaperId(),userAnswerDto);
        return result;

    }

    @PostMapping("/submitExam")
    public void submitExam(@RequestBody ExamSubmitDto examSubmitDto) {

        examsService.submitExam(examSubmitDto);
    }
}
